<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true">
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter.native="handleQuery"
          @input="debounceSearch"
        />
      </el-form-item>
      <el-form-item label="操作模块" prop="module">
        <el-input
          v-model="queryParams.module"
          placeholder="请输入操作模块"
          clearable
          @keyup.enter.native="handleQuery"
          @input="debounceSearch"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="type">
        <el-select
          v-model="queryParams.type"
          placeholder="操作类型"
          clearable
          style="width: 200px"
          @change="getList"
        >
          <el-option label="查询" value="查询" />
          <el-option label="新增" value="新增" />
          <el-option label="修改" value="修改" />
          <el-option label="删除" value="删除" />
          <el-option label="登录" value="登录" />
          <el-option label="注销" value="注销" />
        </el-select>
      </el-form-item>
      <el-form-item label="操作状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="操作状态"
          clearable
          style="width: 200px"
          @change="getList"
        >
          <el-option label="成功" :value="1" />
          <el-option label="失败" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleBatchDelete"
          v-hasPermi="['system:log:remove']"
        >批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="handleClean"
          v-hasPermi="['system:log:clean']"
        >清空</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:log:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <!-- 表格区域 -->
    <el-table :data="logList" ref="table" @row-click="handleRowClick" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="日志编号" align="center" prop="id" width="100" />
      <el-table-column label="用户名称" align="center" prop="username" />
      <el-table-column label="操作模块" align="center" prop="module" width="120" />
      <el-table-column label="操作类型" align="center" prop="type" width="108" />
      <el-table-column label="操作描述" align="center" prop="description" />
      <el-table-column label="请求方法" align="center" prop="method" width="120" />
      <el-table-column label="请求地址" align="center" prop="url" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="请求IP" align="center" prop="ip" width="130" />
      <el-table-column label="操作状态" align="center" prop="status" width="80">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '成功' : '失败' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="执行时间" align="center" prop="costTime" width="100">
        <template #default="scope">
          <span>{{ scope.row.costTime }} ms</span>
        </template>
      </el-table-column>
      <el-table-column label="操作时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
            v-hasPermi="['system:log:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:log:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <el-pagination
        v-model="queryParams.currentPage"
        :page-size="queryParams.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 日志详情弹窗 -->
    <el-dialog title="日志详情" v-model="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作用户：">{{ form.username }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作模块：">{{ form.module }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作类型：">{{ form.type }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作状态：">
              <el-tag :type="form.status === 1 ? 'success' : 'danger'">
                {{ form.status === 1 ? '成功' : '失败' }}
              </el-tag>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作时间：">{{ form.createTime }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求方法：">{{ form.method }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求地址：">{{ form.url }}</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="操作描述：">{{ form.description }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="请求IP：">{{ form.ip }}</el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="执行时间：">{{ form.costTime }} ms</el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="请求参数：">
              <el-input type="textarea" rows="5" v-model="form.params" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.errorMsg">
            <el-form-item label="错误信息：">
              <el-input type="textarea" rows="5" v-model="form.errorMsg" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="form.result">
            <el-form-item label="返回结果：">
              <el-input type="textarea" rows="8" v-model="form.result" readonly />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listSysLog, getSysLog, deleteSysLog, batchDeleteSysLog, cleanSysLog } from "@/api/sysLog";
import { formatJson } from "@/utils";
import { download } from "@/utils/download";

export default {
  name: "SysLog",
  data() {
    return {
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 表格数据
      logList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日志详情表单
      form: {},
      // 查询参数
      queryParams: {}
    };
  },
  methods: {
    // 防抖搜索函数
    debounceSearch() {
      if (this.searchTimer) {
        clearTimeout(this.searchTimer);
      }

      //setTimeout函数 延迟触发或者是延迟加载
      //searchTimer是定时器, 是setTimeout函数的返回值, 其中记录着定时任务
      //如果用户在250毫秒期间继续输入, 那么会清除旧的定时器, 即清除尚未执行的搜索
      this.searchTimer = setTimeout(() => {
        this.getList();
      }, 250);
    },
    // 获取日志列表
    getList() {
      listSysLog(this.queryParams).then(response => {
        if (response.code === 200) {
          this.logList = response.data.records;
          this.total = response.data.total;
        } else {
          this.logList = [];
          this.total = 0;
        }
      })
    },
    // 查询按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮操作
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.queryParams = {};
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    // 查看日志详情
    handleView(row) {
      this.open = true;
      getSysLog(row.id).then(response => {
        if (response.code === 200) {
          const data = response.data;
          // 格式化JSON字符串显示
          if (data.params && typeof data.params === 'string') {
            try {
              data.params = formatJson(data.params);
            } catch (e) {
              // 如果解析失败，保持原样显示
            }
          }
          if (data.result && typeof data.result === 'string') {
            try {
              data.result = formatJson(data.result);
            } catch (e) {
              // 如果解析失败，保持原样显示
            }
          }
          this.form = data;
        }
      });
    },
    // 删除按钮操作
    handleDelete(row) {
      this.$confirm('是否确认删除日志编号为"' + row.id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return deleteSysLog(row.id);
      }).then(response => {
        if (response.code === 200) {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.getList();
        } else {
          this.$message.error(response.msg);
        }
      }).catch(() => {});
    },
    // 批量删除按钮操作
    handleBatchDelete() {
      if (this.ids.length === 0) {
        this.$message.warning("请选择要删除的数据");
        return;
      }
      this.$confirm('是否确认删除选中的' + this.ids.length + '条数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return batchDeleteSysLog(this.ids.join(","));
      }).then(response => {
        if (response.code === 200) {
          this.$message({
            message: "删除成功",
            type: "success"
          });
          this.getList();
        } else {
          this.$message.error(response.msg);
        }
      }).catch(() => {});
    },
    // 清空日志按钮操作
    handleClean() {
      this.$confirm('是否确认清空所有日志数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        return cleanSysLog();
      }).then(response => {
        if (response.code === 200) {
          this.$message({
            message: "清空成功",
            type: "success"
          });
          this.getList();
        } else {
          this.$message.error(response.msg);
        }
      }).catch(() => {});
    },
    // 导出按钮操作
    handleExport() {
      this.$confirm('是否确认导出所有系统日志数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        download('/api/system/log/export', this.ids, '系统日志.xlsx');
      }).catch(() => {});
    },
    // 处理行点击
    handleRowClick(row) {
      this.$refs.table.toggleRowSelection(row);
    },
    // 分页切换
    handleSizeChange(pageSize) {
      this.queryParams.pageSize = pageSize;
      this.getList();
    },
    handleCurrentChange(currenPage) {
      this.queryParams.pageNum = currenPage;
      this.getList();
    },
  },
  created() {
    this.getList();

    // 添加ResizeObserver错误捕获
    window.addEventListener('error', (e) => {
      if (e && e.message && (
          e.message === 'ResizeObserver loop limit exceeded' ||
          e.message.includes('ResizeObserver loop completed with undelivered notifications')
      )) {
        const resizeObserverErr = e;
        resizeObserverErr.stopImmediatePropagation();
      }
    }, true);
  },
};
</script>
